package com.iteaj.iot.serial;

import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortEvent;
import com.fazecast.jSerialComm.SerialPortPacketListener;
import com.iteaj.iot.ProtocolHandle;

public class SerialPortPacketProtocolListener implements SerialPortPacketListener {

    private int packetSize;
    private SerialEventProtocol eventProtocol;
    private ProtocolHandle<SerialEventProtocol> handle;
    public SerialPortPacketProtocolListener(int packetSize, SerialConnectProperties properties, SerialEventProtocolHandle handle) {
        this.handle = handle;
        this.packetSize = packetSize;
        this.eventProtocol = new SerialEventProtocol(null, properties);
    }

    @Override
    public int getPacketSize() {
        return packetSize;
    }

    @Override
    public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_RECEIVED
                | SerialPort.LISTENING_EVENT_DATA_WRITTEN
                | SerialPort.LISTENING_EVENT_DATA_AVAILABLE
                | SerialPort.LISTENING_EVENT_PORT_DISCONNECTED;
    }

    @Override
    public void serialEvent(SerialPortEvent event) {
        this.handle.handle(this.eventProtocol.setEvent(event));
    }
}
